package com.io.filter;

import cn.hutool.json.JSONUtil;
import com.io.config.AuthorizationConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * The class/interface 自定义全局过滤器，统一认证
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@Component
@Slf4j
public class AuthorizationGlobeFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthorizationConfig authenticationConfig;

    // 过滤器逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、获取URL
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        String url = exchange.getRequest().getURI().getPath();

        // 2、是否为不需要验证的公共资源，如果在忽略的列表里,则直接返回
        if (url.contains("/static/") || authenticationConfig.getExcludeUrls().contains(url)) {
            return chain.filter(exchange);
        }

        // 3、获取Token，判断是否有token
        String token = serverHttpRequest.getHeaders().getFirst("Authorization");
        if (!StringUtils.hasText(token)) {
            return authError(serverHttpResponse);
        }

        // 4、解密token，验证token是否有效

        // 5、验证是否有权限资源，应该先从redis根据id取，取不出再从数据库查

        return chain.filter(exchange);
    }

    private Mono<Void> authError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String returnStr;
        returnStr = JSONUtil.toJsonStr(new HashMap<String, Object>() {
            {
                put("resCode", HttpStatus.UNAUTHORIZED.value());
                put("resMsg", "请登陆");
            }
        });
        DataBuffer buffer = response.bufferFactory().wrap(returnStr.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(buffer));
    }

    // 标识当期过滤器的优先级别，返回值越小，优先级越高
    @Override
    public int getOrder() {
        return -1;
    }
}
